/************************************************************************************/
/*  Program name CAPAMEEXT_RULES_USAGES.sql	                                            */
/*  Creater:  Chan Billy Ka Keung (PCCW - UniHub)                                   */
/*************   History   *************************                                */
/* 19 APR, 2006   CHAN Billy Ka Keung         First created                         */
/************************************************************************************/

ALTER SESSION SET NLS_DATE_FORMAT='YYYYMMDD HH24:MI:SS';
SET SERVEROUTPUT ON SIZE 1000000;
SET VERIFY OFF

DECLARE
	lv_Prog_ID				VARCHAR2(100)	:=	'CAPAMEEXT_RULES_USAGES';

	lv_FileName				VARCHAR2(100)	:=	'CAPAME_RULES_USAGES.dat';
	lv_PathName				VARCHAR2(100)	:=	'/tmp';
	lv_UTL_File				UTL_FILE.FILE_TYPE;

	lv_Scc_Count			NUMBER			:=	0;
	lv_Err_Count			NUMBER			:=	0;
	lv_Err_Msg				VARCHAR2(500)	:=	'No Error';

	lv_NGO_Name				VARCHAR2(100);
	lv_NGO_Count			NUMBER;

	CURSOR Cur_F(p_NGO VARCHAR2) IS 
		select * from 
		ame_rule_usages
		where rule_id in (
							select rule_id
							from ame_rules
							where SUBSTR(description,1,4) = p_NGO)
		and item_id = -1;

BEGIN
	lv_NGO_Name		:=	UPPER('&1');	

	SELECT	COUNT('A')
	INTO	lv_NGO_Count
	FROM	HR_ALL_ORGANIZATION_UNITS
	WHERE	SUBSTR(Name,4,4)	=	lv_NGO_Name;

	IF	lv_NGO_Count	>=	1	THEN
		lv_UTL_File		:=	UTL_FILE.FOpen(lv_PathName, lv_FileName, 'w');
		FOR C1 IN Cur_F(lv_NGO_Name) LOOP
			UTL_FILE.PUT_LINE(
				lv_UTL_File,
				C1.ITEM_ID           ||CHR(9)||
				C1.USAGE_TYPE        ||CHR(9)||
				C1.RULE_ID           ||CHR(9)||
				C1.CREATED_BY        ||CHR(9)||
				C1.CREATION_DATE     ||CHR(9)||
				C1.LAST_UPDATED_BY   ||CHR(9)||
				C1.LAST_UPDATE_DATE  ||CHR(9)||
				C1.LAST_UPDATE_LOGIN ||CHR(9)||
				C1.START_DATE        ||CHR(9)||
				C1.END_DATE          ||CHR(9)||
				C1.SECURITY_GROUP_ID ||CHR(9)||
				C1.PRIORITY          
			);
			lv_Scc_Count	:=	lv_Scc_Count	+	1;
		END LOOP;
		UTL_FILE.FClose(lv_UTL_File);
		IF	lv_Scc_Count	=	0	THEN
			lv_Err_Msg	:=	lv_NGO_Name||': No request sets for this business group';
		END IF;
	ELSE
		lv_Err_Count	:=	lv_Err_Count + 1;
		lv_Err_Msg		:=	lv_NGO_Name||': No such NGO exists';
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);

	COMMIT;
END;
/
